package com.kotodama.application.cqrs.bus;

import com.kotodama.application.cqrs.queries.Query;
import com.kotodama.application.cqrs.handlers.QueryHandler;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 查询总线，负责将查询分发到相应的处理器
 */
@Component
public class QueryBus {

    private final Map<Class<? extends Query<?>>, QueryHandler<?, ?>> handlers = new HashMap<>();

    public QueryBus(List<QueryHandler<?, ?>> queryHandlers) {
        queryHandlers.forEach(handler -> handlers.put(handler.getSupportedQueryType(), handler));
    }

    /**
     * 执行查询
     * 
     * @param query 要执行的查询
     * @param <R>   返回结果类型
     * @return 查询结果
     */
    @SuppressWarnings("unchecked")
    public <R> R execute(Query<R> query) {
        QueryHandler<Query<R>, R> handler = (QueryHandler<Query<R>, R>) handlers.get(query.getClass());

        if (handler == null) {
            throw new IllegalArgumentException("未找到查询处理器: " + query.getClass().getSimpleName());
        }

        return handler.handle(query);
    }
}